package com.byit.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.byit.EncryptType.MD5;
import com.byit.builder.MapBuilder;
import com.byit.constant.DefaultValue;
import com.byit.domain.AppBanner;
import com.byit.domain.AppMessageNotice;
import com.byit.domain.AppUser;
import com.byit.domain.vo.DictVo;
import com.byit.dx.SendMessService;
import com.byit.enums.PromptInfo;
import com.byit.jgpush.JgPushExtra;
import com.byit.jgpush.JgPushService;
import com.byit.log.ChannelType;
import com.byit.log.Log;
import com.byit.log.OperatorType;
import com.byit.mail.SendMailService;
import com.byit.msg.MessageResult;
import com.byit.service.IAppMessageNoticeService;
import com.byit.service.IAppNewsService;
import com.byit.service.IAppUserService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.StringUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName AppMessageNoticeController
 * @Description 消息通知
 * @Author lxp
 * @Date 2019-01-02 17:20
 **/
@RestController
@RequestMapping("/api/sys/appMessageNotice")
public class AppMessageNoticeController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IAppMessageNoticeService appMessageNoticeService;

    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private JgPushService jgPushService;
    @Autowired
    private IAppNewsService appNewsService;

    /**
     * 新增或修改消息通知信息
     *
     * @param session
     * @param appMessageNotice
     * @return
     */
    @PostMapping("/add")
    @Log(title = "消息通知", operate = OperatorType.DATA_INSERT, channel = ChannelType.WEB_INTER)
    public Object insertAppMessageNotice(HttpSession session, AppMessageNotice appMessageNotice) {

        Long userId = SessionHelper.getUserId(session);
        try {
            if (null == appMessageNotice) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }

            appMessageNotice.setCreateTime(new Date());
            appMessageNotice.setUpdateTime(new Date());

            //// 加密用户密码
            appMessageNotice.setOperationId(userId);
            appMessageNoticeService.insertOrUpdate(appMessageNotice);
            /**
             * 审核通过 TODO.....
             */

            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }


    /**
     * 修改消息通知信息
     *
     * @param session
     * @param appMessageNotice
     * @return
     */
    @PostMapping("/edit")
    @Log(title = "消息通知", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
    public Object edit(HttpSession session, AppMessageNotice appMessageNotice) {

        Long userId = SessionHelper.getUserId(session);
        //校验
        if (appMessageNoticeService.selectById(appMessageNotice.getId()).getIsCheck()==1) {
            return MessageResult.error("已发布,不能编辑");
        }
        try {
            if (null == appMessageNotice) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }
            if (appMessageNotice.getId() != 0) {
                appMessageNotice.setUpdateTime(new Date());
            }
            //// 加密用户密码
            appMessageNotice.setOperationId(userId);
            appMessageNoticeService.insertOrUpdate(appMessageNotice);

            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 通过Id查询消息通知
     *
     * @param id
     * @return
     */
    @GetMapping("/details")
    @Log(title = "消息通知", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object selectAppMessageNoticeById(@RequestParam("id") Integer id) {
        AppMessageNotice sysCompany = appMessageNoticeService.selectById(id);
        return MessageResult.success(sysCompany);
    }

    /**
     * 按照条件查询消息通知
     *
     * @param session
     * @param title
     * @param level
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    @Log(title = "消息通知", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object selectAppMessageNoticeAll(HttpSession session,
                                            @RequestParam(value = "title", defaultValue = "") String title,
                                            @RequestParam(value = "level", defaultValue = "") String level,
                                            @RequestParam(value = "type", defaultValue = "") String type,
                                            @RequestParam(value = "isCheck", defaultValue = "") String isCheck,
                                            @RequestParam(value = "category", defaultValue = "") String category,
                                            @RequestParam(value = "page", defaultValue = DefaultValue.PAGE_FIRST) int page,
                                            @RequestParam(value = "limit", defaultValue = DefaultValue.PAGE_SIZE) int limit) {
        Page<AppMessageNotice> pageInfo = new Page<>(page, limit);
        Map<String, Object> params = MapBuilder.newMap(5)
                .setParam("title", title)
                .setParam("level", level)
                .setParam("type", type)
                .setParam("category", category)
                .setParam("isCheck", isCheck).ok();
        if (null != title && !"".equals(title)) {
            params.put("title", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(title) + "%");
        }
        Page<JSONObject> result = appMessageNoticeService.selectAppMessageNoticeAll(pageInfo, params);
        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, result);
    }

    /**
     * 逻辑删除消息通知信息
     *
     * @param session
     * @param ids
     * @return
     */
    @PostMapping("/del")
    @Log(title = "消息通知", operate = OperatorType.DATA_DELETE, channel = ChannelType.WEB_INTER)
    public Object delAppMessageNoticeByIds(HttpSession session, @RequestParam("ids") String ids) {
        Long userId = SessionHelper.getUserId(session);
        List<Long> idList = StringUtil.splitLong(ids, ",");
        Map<String, Object> map = MapBuilder.newMap(3).setParam("updateTime", new Date()).setParam("operId", userId).ok();

        for (Long id : idList) {
            if (appMessageNoticeService.selectById(id).getIsCheck()==1) {
                return MessageResult.error("已审核,不能删除");
            }
            map.put("id", id);
            appMessageNoticeService.delAppMessageNoticeById(map);
        }
        return MessageResult.success();
    }


    /**
     * 通知公告
     */
    @GetMapping("/appMessageNotice")
    @Log(title = "消息通知", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object getNewsType(HttpSession session,
                              @RequestParam(value = "title", defaultValue = "") String title) {


        List<JSONObject> appMessageNotice = appMessageNoticeService.getAppNewsType(null);
        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, appMessageNotice);
    }

    /**
     * 发布通知公告
     */
    @PostMapping("/publish")
    @Log(title = "消息通知", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
    public Object publishMessage(HttpSession session,
                                 @RequestParam("id") Long id,
                                 @RequestParam(value = "telNms", defaultValue = "") String telNms,
                                 @RequestParam(value = "isCheck") String isCheck) {
//        EntityWrapper<AppMessageNotice> wrapper = new EntityWrapper<>();
//       // wrapper.setSqlSelect("id,picture,url,title,priority,by_order as byOrder");
//        wrapper.eq("id", id);
//        wrapper.eq("isCheck", isCheck);
        AppMessageNotice appMessageNotice = new AppMessageNotice();
        appMessageNotice.setId(id);
        appMessageNotice.setIsCheck(Integer.valueOf(isCheck));

        try {
            //审核成功
            if (appMessageNotice.getIsCheck()==0) {
               return MessageResult.warpper("001", null, "已发布");
            }
            boolean bol = appMessageNoticeService.updateById(appMessageNotice);
            if (true) {
                AppMessageNotice messageInfo = appMessageNoticeService.selectById(id);
                //审核通过
                if (messageInfo.getIsCheck().equals(1) && messageInfo.getIsPush()==1) {
                    //发布者 默认0 0:系统公告 1.政府公告
                    try {
                        /**
                         * 类型 接收类型 0 推送 1短信 2一起',
                         */
                        JSONObject param = new JSONObject();

                        param.put("msg", messageInfo.getMsg());
                        param.put("title", messageInfo.getTitle());
                        /**
                         * 自定义内容
                         */
                        JgPushExtra extra = new JgPushExtra();
                        /**/
                        extra.setType(3);
                        extra.setLevel(2);
                        extra.setContent(messageInfo.getContent());
                        extra.setTitle("消息通知");
                        extra.setTime(new Date());
                        extra.setSource("智慧江油");
                        param.put("data", extra);
                        /**
                         * 推送
                         */
                        String[] tels = telNms.split(",");
                      //  if (messageInfo.getType()==0) {
//
                            /*全部推送*/
                            jgPushService.jpushAllByAndroidIOS(param);

                       // } else if (messageInfo.getType()==1) {
                            /*发短信*/
                        /*    for (String tel : tels) {
                                SendMessService.sendSms(messageInfo.getContent(), tel);
                            }*/

                       // } else if (messageInfo.getType()==2) {
                            /*推送 ,短信一起*/
                           /* for (String tel : tels) {
                                AppUser appUser = appUserService.selectByPhone(tel);
                                param.put("alias", MD5.md5(appUser.getDeviceId() + ":" + appUser.getId()));
                                *//*推送*//*
                                jgPushService.jpushAndroidIOSByAlias(param);
                                *//*短信*//*
                                SendMessService.sendSms(messageInfo.getContent(), tel);
                            }

                        }*/
                    } catch (Exception e) {
                        MessageResult.warpper("001", null, "推送失败");
                    }
                }else{
                    MessageResult.warpper("001", null, "未发布");
                }
                return MessageResult.warpper("000", null, "推送成功");
            }
        } catch (Exception e) {
            return MessageResult.error(e.getMessage());
        }
        return MessageResult.warpper("000", null, "发布成功");
    }


    /**
     * 推送通知公告
     * TODO ....
     */
//    @PostMapping("/push")
//    @Log(title = "消息通知", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
//    public Object push(HttpSession session,
//                       @RequestParam(value = "id", defaultValue = "") Long id,
//                       @RequestParam(value = "title", defaultValue = "") String title,
//                       @RequestParam(value = "type", defaultValue = "") String type,
//                       @RequestParam(value = "telNms", defaultValue = "") String telNms,
//                       @RequestParam(value = "isCheck", defaultValue = "") String isCheck) {
//
//        AppMessageNotice messageInfo = appMessageNoticeService.selectById(id);
        //审核通过
//        if (messageInfo.getIsCheck().equals(1)) {
//            //发布者 默认0 0:系统公告 1.政府公告
//            // param.put("publisher", messageInfo.getPublisher().toString());
//            try {
//                /**
//                 * 类型 接收类型 0 推送 1短信 2一起',
//                 */
//                JSONObject param = new JSONObject();
//
//                param.put("msg", messageInfo.getMsg());
//                param.put("title", messageInfo.getTitle());
//                /**
//                 * 自定义内容
//                 */
//                JgPushExtra extra = new JgPushExtra();
//                /**/
//                extra.setType(5);
//                extra.setLevel(2);
//                extra.setContent(messageInfo.getContent());
//                extra.setTitle("消息通知");
//                extra.setTime(new Date());
//                extra.setSource("智慧江油");
//                param.put("data", extra);
//                /**
//                 * 推送
//                 */
//                String[] tels = telNms.split(",");
//                if (type.equals("0")) {
//
//                    /**
//                     * 单个用户
//                     */
//                    if (tels.length == 1) {
//                        AppUser appUser = appUserService.selectByPhone(telNms.split(",")[0]);
//                        param.put("alias", MD5.md5(appUser.getDeviceId() + ":" + appUser.getId()));
//                        /*单个用户推送*/
//                       // for (String tel : tels) {
//                            param.put("alias", MD5.md5(appUser.getDeviceId() + ":" + appUser.getId()));
//                            jgPushService.jpushAndroidIOSByAlias(param);
//                        //}
//                    } else if (telNms.length() > 1) {
//                        /*多个用户推送*/
//                        for (String tel : tels) {
//                            AppUser appUser = appUserService.selectByPhone(tel);
//                            param.put("alias", MD5.md5(appUser.getDeviceId() + ":" + appUser.getId()));
//                            jgPushService.jpushAndroidIOSByAlias(param);
//                        }
//                    } else {
//                        /*全部推送*/
//                        jgPushService.jpushAllByAndroidIOS(param);
//                    }
//
//                } else if (type.equals("1")) {
//                    /*发短信*/
//                    for (String tel : tels) {
//                        SendMessService.sendSms(messageInfo.getContent(), tel);
//                    }
//
//                } else if (type.equals("2")) {
//                    /*推送 ,短信一起*/
//                    for (String tel : tels) {
//                        AppUser appUser = appUserService.selectByPhone(tel);
//                        param.put("alias", MD5.md5(appUser.getDeviceId() + ":" + appUser.getId()));
//                        /*推送*/
//                        jgPushService.jpushAndroidIOSByAlias(param);
//                        /*短信*/
//                        SendMessService.sendSms(messageInfo.getContent(), tel);
//                    }
//
//                }
//            } catch (Exception e) {
//                MessageResult.warpper("001", null, "推送失败");
//            }
//        }else{
//            MessageResult.warpper("001", null, "未发布");
//        }
//        return MessageResult.warpper("000", null, "推送成功");
        //    }


}
